package com.github.gin.sns.util;

import com.github.gin.sns.annotation.XmlRoot;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

import java.io.Writer;

/**
 * Created by GinPonson on 2017/1/1.
 */
public class XStreamUtil {
    private static XStream xstream = null;

    //new XppDriver(new XmlFriendlyNameCoder("_-", "_"))
    public static XStream getInstance(){
        if(xstream == null){
            synchronized (XStreamUtil.class) {
                if(xstream == null){
                    xstream = new XStream(new CDATAXppDriver());
                    //根据注解读取
                    xstream.processAnnotations(AnnotationScaner.findClassByAnnotation(XmlRoot.class));
                    xstream.autodetectAnnotations(true);
                    xstream.ignoreUnknownElements();
                }
            }
        }
        return xstream;
    }

    static class CDATAXppDriver extends XppDriver {
        @Override
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                @Override
                protected void writeText(QuickWriter writer, String text) {
                    writer.write(cDATA(text));
                }
            };
        }
    }


    private static String cDATA(String text){
        return "<![CDATA["+text+"]]>";
    }


}
